package com.qf.controller;

import com.qf.utils.RedisLockUtil;
import org.apache.curator.framework.CuratorFramework;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

/**
 * @author 千峰教育
 * @Company http://www.mobiletrain.org/
 * @Version 1.0
 */

@RestController
@RequestMapping("/redis")
public class TestRedisController {

    //1. 准备商品的库存
    public static Map<String,Integer> itemStock = new HashMap<>();

    //2. 准备商品的订单
    public static Map<String,Integer> itemOrder = new HashMap<>();

    static {
        itemStock.put("牙刷", 1000);
        itemOrder.put("牙刷", 0);
    }

    @Autowired
    CuratorFramework client;


    @Autowired
    RedisLockUtil redisLockUtil;


    @RequestMapping("/kill")
    public String kill(String item) throws Exception {
        //如果获取锁成功，执行业务代码
        if( redisLockUtil.lock(item , System.currentTimeMillis() + "" , 5) ) {
            //减库存
            Integer stock = itemStock.get(item);
            if(stock <= 0){
                return item +"卖完了 ---- " + item+"还剩下: " + itemStock.get(item)
                        + "，已卖" + item  + ":" + itemOrder.get(item);
            }

            Thread.sleep(100);
            //库存减一
            itemStock.put(item, stock - 1);

            //增加订单
            Thread.sleep(100);
            itemOrder.put(item, itemOrder.get(item) + 1);


            redisLockUtil.unlock(item);
        }

        return item+"还剩下: " + itemStock.get(item) + "，已卖" + item  + ":" + itemOrder.get(item);
    }

}
